package com.aaa.tars.controller;

import com.aaa.tars.util.Result;
import com.aaa.tars.util.ResultUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * @FileName: UploadController
 * @Description:
 * @Author: xm
 * @CreateTime: 2025/9/9 16:35
 * @Version: 1.0.0
 */
@RestController
@RequestMapping("/upload")
public class UploadController {

    @PostMapping("/image")
    public Result uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResultUtil.error("文件不能为空");
        }

        try {
            // 获取原始文件名
            String originalFilename = file.getOriginalFilename();
            // 获取文件后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 生成唯一文件名
            String fileName = UUID.randomUUID().toString() + suffix;

            // 保存路径（建议使用绝对路径或云存储）
            String uploadPath = "C:/uploads/images/";
            File dir = new File(uploadPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }


            // 保存文件
            File dest = new File(uploadPath + fileName);
            file.transferTo(dest);

            // 返回访问路径（如：/images/xxx.jpg）
            String imageUrl = "/images/" + fileName;

            return ResultUtil.success(imageUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("上传失败：" + e.getMessage());
        }
    }
}
